package queue;

import java.util.Arrays;
import java.util.NoSuchElementException;

public class ArrayQueue<E> implements Queue<E> {

    private static int DEFAULT_LENGTH = 8;
    private Object[] queue;
    private int size;

    public ArrayQueue(){
        this(DEFAULT_LENGTH);
    }

    public ArrayQueue(int length){
        if (length < 0)
            throw new IllegalArgumentException("Queue length has to be non-negative");
        queue = new Object[length];
    }

    @Override
    public E element() {
        if (size == 0)
            throw new NoSuchElementException("Queue is empty");
        return (E) queue[0];
    }

    @Override
    public boolean offer(E e) {
        if(size == queue.length)
            queue = Arrays.copyOf(queue, queue.length * 2 + 1);
        queue[size] = e;
        size++;
        return true;
    }

    @Override
    public E peek() {
        if(size == 0)
            return null;
        return (E) queue[0];
    }

    @Override
    public E poll() {
        if(size == 0)
            return null;
        E head = (E) queue[0];
        queue = Arrays.copyOfRange(queue, 1, queue.length + 1);
        size--;
        return head;
    }

    @Override
    public E remove() {
        if (size == 0)
            throw new NoSuchElementException("Queue is empty.");
        E head = (E) queue[0];
        queue = Arrays.copyOfRange(queue, 1, queue.length + 1);
        size--;
        return head;
    }
}
